﻿using System.Windows;
using System.Windows.Interactivity;
using System.Windows.Input;

namespace NthDownload.Common.Interactivity.Triggers
{
    public class KeyTrigger : TriggerBase<UIElement>
    {
        #region Override Methods

        protected override void OnAttached()
        {
            base.OnAttached();

            AssociatedObject.KeyDown -= AssociatedObjectKeyDown;
            AssociatedObject.KeyDown += AssociatedObjectKeyDown;
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();

            AssociatedObject.KeyDown -= AssociatedObjectKeyDown;
        }

        #endregion Override Methods

        #region Event Handlers
        
        private void AssociatedObjectKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key && Keyboard.Modifiers == ModifierKeys)
            {
                InvokeActions(e);
            }
        }

        #endregion Event Handlers

        #region Dependancy Properties

        #region Key

        public Key Key
        {
            get { return (Key)GetValue(KeyProperty); }
            set { SetValue(KeyProperty, value); }
        }

        // Using a DependencyProperty as the backing store for Key.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty KeyProperty =
            DependencyProperty.Register("Key", typeof(Key), typeof(KeyTrigger));
        
        #endregion Key

        #region Key Modifiers

        public ModifierKeys ModifierKeys
        {
            get { return (ModifierKeys)GetValue(ModifierKeysProperty); }
            set { SetValue(ModifierKeysProperty, value); }
        }

        // Using a DependencyProperty as the backing store for MyProperty.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty ModifierKeysProperty =
            DependencyProperty.Register("ModifierKeys", typeof(ModifierKeys), typeof(KeyTrigger));

        #endregion Key Modifiers

        #endregion Dependancy Properties
    }
}
